<?php

class UserController extends Zend_Controller_Action {

    protected $_model = null;
    protected $_acl = null;

    public function preDispatch() {
        if (!Zend_Auth::getInstance()->hasIdentity()) {
//            //            // If the user is logged in, we don't want to show the login form;
//            //            // however, the logout action should still be available
//            if ('logout' != $this->getRequest()->getActionName()) {
//                $this->_redirect($this->getRequest()->g);
//            }
//        } else {
            // If they aren't, they can't logout, so that action should 
            // redirect to the login form
            if ('logout' == $this->getRequest()->getActionName()) {
                $this->_redirect('user/login');
            }
        }
    }

    public function init() {
        
    }

    public function indexAction() {
//        if (!Zend_Auth::getInstance()->hasIdentity())
//            $this->_redirect('user/login');
        $this->_acl = new Middleman_Acl(Zend_Auth::getInstance());
        if (!$this->_acl->isAllowed('login', $this->_request->getControllerName(), $this->_request->getActionName())) {
            echo '<br>Ban khong duoc quyen truy cap vao action nay';
        }
    }

    public function loginAction() {

        $this->_helper->layout()->setLayout('login');
        $this->_helper->layout()->headTitle = 'Log in Middleman';
        //get timelife of session in Appplication.ini 
        $option = $this->getInvokeArg('bootstrap')->getOptions();

        $user = new Application_Model_DbTable_User();
        if ($this->getRequest()->isPost()) {
            $data = $this->_request->getParams();
            $auth = Zend_Auth::getInstance();
            $authAdapter = new Zend_Auth_Adapter_DbTable($user->getAdapter(), 'users');
            $authAdapter->setIdentityColumn('username')
                    ->setCredentialColumn('password');
            $authAdapter->setIdentity($data['username'])
                    ->setCredential(hash($option['hash_method'], $data['password']));
            $result = $auth->authenticate($authAdapter);
            if ($result->isValid()) {
                $storage = new Zend_Auth_Storage_Session();
                $storage->write($authAdapter->getResultRowObject());

                //update column last_login
                $user->update(array('last_login' => time()), "id = " . $auth->getIdentity()->id);

                //remember me
                if (isset($data['remember']))
                    Zend_Session::rememberMe($option['lifetime']);
                $this->_redirect('index');
                //print_r(Zend_auth::getInstance()->getIdentity());
            } else {
                $this->view->errorMessage = "Invalid username or password. Please try again.";
            }
        }
    }

    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $storage = new Zend_Auth_Storage_Session();
        $storage->clear();
        Zend_Session::forgetMe();
        $this->_redirect('user/login');
    }

    public function testAction() {
//        $user_model = new Application_Model_DbTable_User();
//        $user = $user_model->find(85);
//        $user81 = $user->current();
//        $role = $user81->findManyToManyRowset('Application_Model_DbTable_Role', 'Application_Model_DbTable_RoleUser');
//        print_r($role);
//        foreach ($role as $value) {
//            print ("<br>" . $value->id);
//            print("<dd>" . $value->name);
//        }die();
        $g = new Application_Model_ProjectMapper();
        $gb = $g->find(2);
//        $g= new Application_Model_DbTable_Project();
//        $gb = $g->find(2);
        print_r($gb);die();
    }

    public function profileAction() {
        $id = $this->_request->getParam('id');
        if (!((int) $id > 0)) {
            $this->_redirect('/user/list');
        }
        $user = new Application_Model_DbTable_User();
        //get user info whose id = $id
        $user = $user->find($id)->current();
        //assign $user to view
        $this->view->user = $user;
    }

    public function listAction() {
        $this->_model = new Application_Model_DbTable_User();
        $users = $this->_model->fetchAll();
        $this->view->users = $users;
    }

    public function addAction() {
        $this->view->headTitle = "Add new user";

        $request = $this->getRequest();
        $this->view->values = array();
        if ($request->isPost()) {
            //set varible values to render view page
            $this->view->values = $request->getParams();
            $option = $this->getInvokeArg('bootstrap')->getOptions();
            //get data of project from $_Post
            $data = array(
                'fullname' => $request->getParam('fullname'),
                'username' => $request->getParam('username'),
                'password' => hash($option['hash_method'], $request->getParam('password')),
                'position' => $request->getParam('position'),
                'logins' => '',
                'last_login' => '',
                'email' => $request->getParam('email'),
                'tel' => $request->getParam('tel'),
                'yahoo_skype' => $request->getParam('yahoo_skype'),
                'active' => is_null($request->getParam('isActive')) ? 0 : 1,
            );

            //create project and store in database
            $this->_model = new Application_Model_DbTable_User();

            //Return project id (id > 0) if insert successfully
            $user = $this->_model->insert($data);
            if ($user > 0) {
                $this->_redirect('/user/profile/' . $user);
            }
        }
    }

    public function editAction() {
        // action body
    }

    public function deleteAction() {
        // action body
    }

}

